/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.nc.kyiv.yellow.sociallibrary.filters;

import com.nc.kyiv.yellow.sociallibrary.POJO.SessionInfo;
import com.nc.kyiv.yellow.sociallibrary.helper.Coockies;
import com.nc.kyiv.yellow.sociallibrary.helper.MapBuilder;
import com.nc.kyiv.yellow.sociallibrary.helper.Sessions;
import com.nc.kyiv.yellow.sociallibrary.user.CheckLoginAndPass;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Evgeniy Grigorevskiy
 */
public class AuthorizationFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain filterChain) throws IOException, ServletException {

        HttpSession Session = ((HttpServletRequest) request).getSession();
        Sessions sessionActivity = new Sessions();

        PrintWriter out = response.getWriter();

        Coockies coockiesActivity = new Coockies(request, response);

        //mb get from request to DB ...
        Map userRoles = new HashMap<String, String>();
        userRoles.put("4", "guest");
        userRoles.put("5", "beginner");
        userRoles.put("6", "advanced");
        userRoles.put("7", "moderator");

        MapBuilder helper = new MapBuilder();

        //this map has 5 values with keys: "userId","userLogin","userPass","userFirstName","userRole"
        Map userInfo = new HashMap< String, String>();
        try{
        if (request.getParameter("type").toString().equals("onPageLoad")) {

            //check coockies
            if (coockiesActivity.checkIfExistCoockies()) {
                try {
                    coockiesActivity.updateCoockies();
                    // getting userLogin and userPass
                    Map coockiesResult = coockiesActivity.getInfoFromCoockies();

                    StringBuilder postParameters = new StringBuilder();
                    postParameters.append(coockiesResult.get("userLogin"));
                    postParameters.append(helper.getRequestSplitter());
                    postParameters.append(coockiesResult.get("userPass"));
                    //get his params from DB
                    CheckLoginAndPass login = new CheckLoginAndPass();
                    String result = login.execute(postParameters.toString());


                    if (!result.equals("failed")) {
                        String[] mapKeys = {"userId", "userLogin", "userPass", "userFirstName", "userRole"};
                        userInfo = helper.stringToMap(result, mapKeys, helper.getResponceSplitter());
                    } else {
                        coockiesActivity.deleteCoockies();
                        userInfo.put("userId", "guest");
                        userInfo.put("userLogin", "guest");
                        userInfo.put("userPass", "guest");
                        userInfo.put("userFirstName", "guest");
                        userInfo.put("userRole", "4");
                    }
                } catch (Exception ex) {
                    out.print("failed");
                    return;
                }
            } else {
                if (Session.getAttribute(sessionActivity.getSessionInfoAttrName()) == null) {
                    userInfo.put("userId", "guest");
                    userInfo.put("userLogin", "guest");
                    userInfo.put("userPass", "guest");
                    userInfo.put("userFirstName", "guest");
                    userInfo.put("userRole", "4");
                } else {
                    SessionInfo aboutUser = (SessionInfo) Session.getAttribute(sessionActivity.getSessionInfoAttrName());
                    userInfo.put("userId", aboutUser.getUserId());
                    userInfo.put("userLogin", aboutUser.getUserLogin());
                    userInfo.put("userPass", aboutUser.getUserPass());
                    userInfo.put("userFirstName", aboutUser.getUserFirstName());
                    userInfo.put("userRole", aboutUser.getUserRole());
                }
            }

            //create new session
            SessionInfo aboutUser = new SessionInfo();
            aboutUser.setUserId(userInfo.get("userId").toString());
            aboutUser.setUserLogin(userInfo.get("userLogin").toString());
            aboutUser.setUserPass(userInfo.get("userPass").toString());
            aboutUser.setUserFirstName(userInfo.get("userId").toString());
            aboutUser.setUserRole(userInfo.get("userRole").toString());

            Session = sessionActivity.createNewSession(aboutUser, Session);
            StringBuilder result = new StringBuilder();
            result.append(userInfo.get("userRole"));
            result.append(helper.getResponceSplitter());
            result.append(userInfo.get("userFirstName"));
            out.print(result.toString());
            System.out.println(result.toString());
            System.out.println(userInfo.toString());
            return;
        }

        if (request.getParameter("type").toString().equals("login")) {
            try {

                //get his params from DB
                CheckLoginAndPass login = new CheckLoginAndPass();
                String result = login.execute(request.getParameter("parameters"));

                if (!result.equals("failed")) {
                    String[] mapKeys = {"userId", "userLogin", "userPass", "userFirstName", "userRole"};
                    userInfo = helper.stringToMap(result, mapKeys, helper.getResponceSplitter());
                    coockiesActivity.createCoockies(userInfo.get("userLogin").toString(), userInfo.get("userPass").toString());
                } else {
                    userInfo.put("userId", "guest");
                    userInfo.put("userLogin", "guest");
                    userInfo.put("userPass", "guest");
                    userInfo.put("userFirstName", "guest");
                    userInfo.put("userRole", "4");

                }

                //create new session
                SessionInfo aboutUser = new SessionInfo();
                aboutUser.setUserId(userInfo.get("userId").toString());
                aboutUser.setUserLogin(userInfo.get("userLogin").toString());
                aboutUser.setUserPass(userInfo.get("userPass").toString());
                aboutUser.setUserFirstName(userInfo.get("userId").toString());
                aboutUser.setUserRole(userInfo.get("userRole").toString());

                Session = sessionActivity.createNewSession(aboutUser, Session);
                if (userInfo.get("userRole").toString().equals("4")) {
                    out.print("failed");
                } else {
                    StringBuilder postResult = new StringBuilder();
                    postResult.append(userInfo.get("userRole"));
                    postResult.append(helper.getResponceSplitter());
                    postResult.append(userInfo.get("userFirstName"));
                    out.print(postResult.toString());
                }
                return;
            } catch (Exception ex) {
                out.println("failed");
                return;
            }
        }

        if (request.getParameter("type").toString().equals("logout")) {
            if (coockiesActivity.checkIfExistCoockies()) {
                coockiesActivity.deleteCoockies();
            }
            userInfo.put("userId", "guest");
            userInfo.put("userLogin", "guest");
            userInfo.put("userPass", "guest");
            userInfo.put("userFirstName", "guest");
            userInfo.put("userRole", "4");
            SessionInfo aboutUser = new SessionInfo();
            aboutUser.setUserId(userInfo.get("userId").toString());
            aboutUser.setUserLogin(userInfo.get("userLogin").toString());
            aboutUser.setUserPass(userInfo.get("userPass").toString());
            aboutUser.setUserFirstName(userInfo.get("userId").toString());
            aboutUser.setUserRole(userInfo.get("userRole").toString());
            
            Session = sessionActivity.createNewSession(aboutUser, Session);
            out.print("success");
            return;
        }

        //this map has 5 values with keys: "userId","userLogin","userPass","userFirstName","userRole"
        userInfo = sessionActivity.getMapParametersFromSession(Session);
        if (userInfo == null) {
            //check coockies ... mb session has finished...
            if (coockiesActivity.checkIfExistCoockies()) {
                try {
                    coockiesActivity.updateCoockies();
                    // getting userLogin and userPass
                    Map coockiesResult = coockiesActivity.getInfoFromCoockies();

                    StringBuilder postParameters = new StringBuilder();
                    postParameters.append(coockiesResult.get("userLogin"));
                    postParameters.append(helper.getRequestSplitter());
                    postParameters.append(coockiesResult.get("userPass"));
                    //get his params from DB
                    CheckLoginAndPass login = new CheckLoginAndPass();
                    String result = login.execute(postParameters.toString());

                    if (!result.equals("failed")) {
                        String[] mapKeys = {"userId", "userLogin", "userPass", "userFirstName", "userRole"};
                        userInfo = helper.stringToMap(result, mapKeys, helper.getResponceSplitter());
                    } else {
                        coockiesActivity.deleteCoockies();
                        userInfo.put("userId", "guest");
                        userInfo.put("userLogin", "guest");
                        userInfo.put("userPass", "guest");
                        userInfo.put("userFirstName", "guest");
                        userInfo.put("userRole", "4");
                    }
                } catch (Exception ex) {
                    out.print("failed");
                    return;
                }
            } else {
                userInfo.put("userId", "guest");
                userInfo.put("userLogin", "guest");
                userInfo.put("userPass", "guest");
                userInfo.put("userFirstName", "guest");
                userInfo.put("userRole", "4");
            }
            //create new session
            SessionInfo aboutUser = new SessionInfo();
            aboutUser.setUserId(userInfo.get("userId").toString());
            aboutUser.setUserLogin(userInfo.get("userLogin").toString());
            aboutUser.setUserPass(userInfo.get("userPass").toString());
            aboutUser.setUserFirstName(userInfo.get("userId").toString());
            aboutUser.setUserRole(userInfo.get("userRole").toString());
            
            Session = sessionActivity.createNewSession(aboutUser, Session);
        }

        FilterConfigClass conf = new FilterConfigClass();
        if (Integer.parseInt(userInfo.get("userRole").toString()) >= conf.checkAccess(request.getParameter("type"))) {
            filterChain.doFilter(request, response);
            return;
        } else {
            out.print("failed");
            return;
        }

        
    } catch (Exception ex){
        out.print("failed");
    }
    }
    @Override
    public void destroy() {
    }
}
